/**
 * 结算页
 */
import { getUserAddressList } from '@/api/ajax'
export default {
   namespaced: true,
   state: {
      addressActive: null, // 默认选中的地址选项
      myGoods: JSON.parse(sessionStorage.getItem('myGoods') || '[]'), // 我的订购商品列表
      addressList: [], // 用户的收货地址列表
   },
   actions: {
      /* 获取用户收货地址 */
      async getAddressList(context, username) {
         const { addressList } = await getUserAddressList(username)
         context.commit('GET_ADDRESS_LIST', addressList)
      },
   },
   mutations: {
      /* 获取用户的收货地址 */
      GET_ADDRESS_LIST(state, addressList) {
         state.addressList = addressList.reverse()
      },
      /* 切换默认选中的地址项 */
      TOGGLE_ADDRESS_ACTIVE(state, index) {
         state.addressActive = index === null || undefined ? null : Number(index)
      },
      /* 将购物车中的商品添加到订购商品列表中 */
      ADD_CARTS_TO_MYGOODS(state, carts) {
         // 如果没有则直接加入订购商品列表中
         state.myGoods = JSON.parse(carts)
         sessionStorage.setItem('myGoods', carts)
      },
      /* 清空订购商品列表 */
      CLEAR_MYGOODS(state) {
         state.myGoods = []
         sessionStorage.removeItem('myGoods')
      },
      /* 添加一条数据到地址列表中 */
      ADD_ADDRESS_TO_ADDRESSLIST(state, address) {
         state.addressList.push(address)
      },
      /* 从地址列表中删除一条数据 */
      DEL_ADDRESS_FROM_ADDRESSLIST(state, addressId) {
         state.addressList = state.addressList.filter(item => item.id != addressId)
      },
      /* 更新一条收货地址数据 */
      UPDATE_ADDRESSLIST_BY_ID(state, address) {
         let target = state.addressList.find(item => item.id == address.id)
         for (let key in target) {
            target[key] = address[key]
         }
      },
   },
   getters: {
      /* 订购商品列表总价 */
      getTotalMoney(state) {
         return state.myGoods.reduce((prev, food) => prev += Number(food.price)*Number(food.count), 0)
      }
   }
}